package com.ksl.kinglockguard.gamelock;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.WallpaperManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.RemoteViews;

import com.ksl.kinglockguard.R;
import com.ksl.kinglockguard.activity.DetailPageActivity;
import com.ksl.kinglockguard.activity.GamePlayActivity;
import com.ksl.kinglockguard.activity.LockMainActivity;
import com.ksl.kinglockguard.bitmap.ImageLoader;
import com.ksl.kinglockguard.bitmap.ImageLoader.ILoadedFinishLister;
import com.ksl.kinglockguard.data.Constants;
import com.ksl.kinglockguard.data.SharePreferenceSdkData;
import com.ksl.kinglockguard.data.UserCountHabit;
import com.ksl.kinglockguard.domain.MainList;
import com.ksl.kinglockguard.domain.MainNews;
import com.ksl.kinglockguard.network.MyDownloadManager;
import com.ksl.kinglockguard.network.NetworkTask;
import com.ksl.kinglockguard.service.TimeRunableService;
import com.ksl.kinglockguard.utils.DeleteSdCacheUtil;
import com.ksl.kinglockguard.utils.ImageUtils;
import com.ksl.kinglockguard.utils.KingsReviveMain;
import com.ksl.kinglockguard.utils.KingsSystemUtils;
import com.ksl.kinglockguard.utils.NetUtil;
import com.ksl.kinglockguard.utils.SdcardFileUtil;
import com.ksl.kinglockguard.widget.DateTimeControl;
import com.ksl.kinglockguard.widget.ScreenLockView;
import com.ksl.kinglockguard.widget.ScreenLockView.LockListener;
import com.ksl.kinglockguard.widget.StatusViewManager;
import com.lsk.open.core.MyLog;
import com.lsk.open.core.net.NetConnectTask;
import com.lsk.open.core.net.NetConnectTask.TaskListener;
import com.lsk.open.core.net.NetHeadUtils;
import com.lsk.open.core.serialize_cache.CacheDataManager;
import com.lsk.open.core.utils.KingsFileUtils;
import com.lsk.open.core.utils.ProductInfoUtils;

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public class ScreenLockService extends Service implements DateTimeControl{

	private static final String TAG = "ScreenLockService";
	public static final String SHOW_SMALL_IMAGE = "1";
	private static final int REQUEST_NUM = 20;

	private static final String DEFAULT_WALLPAER = "deflaut_wallpaper";
	private static final String DEFAULT_WALLPAER_BLUR = "deflaut_wallpaper.blur";

	private static ScreenLockView mLockView;
	private static int picNum = 0;
	public static StatusViewManager mStatusViewManager;

	private static boolean isShowKeyGuard = false;

	private static int RQ_TIME = 5 * 60 * 1000;
	private static long mRq_time = RQ_TIME;
	private static int RANDOMTIME = 5 * 60 * 60 * 1000;

	private KeyguardManager mKeyguardManager = null;
	private KeyguardManager.KeyguardLock mKeyguardLock = null;
	private WindowManager mWinManager;
	private WindowManager.LayoutParams mLp = new WindowManager.LayoutParams();

	private View mMask;
	private MainNews curNews;// 维护一个当前新闻的url
	private InCallReceiver mInCallReceiver = new InCallReceiver();
	private TelephonyManager tpm;
	boolean isCalling = false;
	public MainList screenNews;
	private int screenWidth, screenHeight;
	private int newsIndex = 0;
	private int[] mPagesToListIndex = new int[3];
	private ContentResolver mContentResolver;
	private List<MainNews> mDowloadingList;// 保存正在下载列表
	private GestureDetector gd;
//	private int mDowloadPicIndex = -1;// 用于保存正在交替数据两批数据脚标

	private boolean isLoadChecked = false;
	public static int NOTIFY_FIRST = 8900;
	public static int NOTIFY_NETCOUNTER_ID = NOTIFY_FIRST + 6;
	private boolean FLAG_NOTICE = false;
	private Context mContext;
	
	private boolean screenRegisterFlag = false;
	private boolean batteryRegisterFlag = false;
	private boolean wifiRegisterFlag = false;

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
		};
	};

	@Override
	public void onCreate() {
		super.onCreate();
		MyLog.i("jyh5", "~~~~~~ScreenLockService onCreate~~~~");
		mContext = getApplicationContext();
		if (VERSION.SDK_INT < 11)
			stopSelf();
		dealwithOldCacheByCode();//处理kslock目录
		Constants.initFiles();//初始化各个文件夹
		KingsReviveMain.startDaemonProcess(mContext);//启动守护进程
		startLoadTimer();//启动TimeRunnableService
		if(SharePreferenceSdkData.getScreenLockFlag(mContext)){
			EnableKeyGruadPro();
			DisableKeyGruadPro();
			initScreenLock();
			MyLog.i("jyh5", "~~~~~~getScreenLockFlag true~~~~");
		}else
			MyLog.i("jyh5", "~~~~~~getScreenLockFlag false~~~~");
			
	}
	

	/*
	 * 对卸载之后再安装老用户进行目录kslock数据清理以防报错，同时对于vcode >100用户升级不进行数据清理
	 */
	private void dealwithOldCacheByCode() {

		int beforeCode = SharePreferenceSdkData
				.getVersionCode(mContext);

		String strVcode = ProductInfoUtils.vcode;
		if (strVcode == null) {
			strVcode = ProductInfoUtils.getVcode(mContext);
		}
		int currCode = Integer.parseInt(strVcode);

		if (beforeCode == -1) {
			new DeleteSdCacheUtil(true).start();// 对于卸载的老用户进行数据清理
		}
		if (currCode != beforeCode) {
			SharePreferenceSdkData.setVersionCode(mContext,
					currCode);

		}
	}

	/**
	 * 设置背光时间 毫秒
	 */
	private void setScreenOffTime(int paramInt) {
		try {
			// Settings.System.putInt(getContentResolver(),
			// Settings.System.SCREEN_OFF_TIMEOUT, paramInt);
			MyLog.i("ydy", "**setScreenOffTime**   ScreenOffTime == "
					+ paramInt);
		} catch (Exception localException) {
			localException.printStackTrace();
		}
	}

	public void setLockPatternEnabled(boolean enabled) {
		setBoolean(android.provider.Settings.System.LOCK_PATTERN_ENABLED,
				enabled);
	}

	private void setBoolean(String systemSettingKey, boolean enabled) {
		android.provider.Settings.System.putInt(mContentResolver,
				systemSettingKey, enabled ? 1 : 0);
	}

	private void startLoadTimer() {

		timerHandler.removeCallbacks(timeRunnable);
		timerHandler.postDelayed(timeRunnable, 30 * 1000);// 每3分钟执行一次runnable

	}

	private void hideKeyguardView() {
		try {
			isShowKeyGuard = false;
			isAnimating = false;
			try {
				mWinManager.removeView(mLockView);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if(mLockView != null)
							mLockView.resetLock();
						//解锁后释放两个大的背景图Bitmap占用的内存
//						mLockView.recycleBitmap();
					}
				}, 300);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void initWindow(){
		isShowKeyGuard = false;
		mWinManager = (WindowManager) mContext.getSystemService("window");
		mKeyguardManager = (KeyguardManager) mContext
				.getSystemService(Context.KEYGUARD_SERVICE);
		mKeyguardLock = mKeyguardManager.newKeyguardLock(this.getClass().getName());
		WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		if (outMetrics.heightPixels > outMetrics.widthPixels) {
			screenWidth = outMetrics.widthPixels;
			screenHeight = outMetrics.heightPixels;
		} else {
			screenHeight = outMetrics.widthPixels;
			screenWidth = outMetrics.heightPixels;
		}
	}
	
	private void makeWallpaper(){
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(5 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				preMakeWallPaper();// 生成系统锁屏文件
			}
		}).start();
	}
	
	private void setOtherParams(){
		try {
			mContentResolver = getContentResolver();
			setLockPatternEnabled(false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (!KingsSystemUtils.isScreenLocked(mContext)
				&& isIDLE()) {
			mHandler.removeCallbacks(mRefreshRunnable);
			mHandler.post(mRefreshRunnable);
		}
		if (FLAG_NOTICE)
			startForegroundCompat(NOTIFY_NETCOUNTER_ID,getNotification("更多精彩内容,请查看"));
	}

	private void initScreenLock() {
		
		initWindow();//初始化窗口
		
		initViews();//初始化view

		inittLayoutParam();//初始化window参数

		registerComponent();//注册广播
		
		makeWallpaper();// 生成系统锁屏文件
		
		setOtherParams();
	}

	private Handler timerHandler = new Handler() {
	};
	boolean isLoadedAll;
	private Runnable timeRunnable = new Runnable() {
		@Override
		public void run() {
			MyLog.i("jyh5", "~~~~~~timeRunnable run ~~~~");
			Intent intent = new Intent(mContext, TimeRunableService.class);
			startService(intent);
		}
	};

	private void loadCache() {
		if (CacheDataManager.isDataValidate(Constants.FSKEY_NEWlISTS) == 2) {
			MyLog.i("ydy4",
					"ScreenLockService (CacheDataManager.isDataValidate)==2");
			screenNews = (MainList) CacheDataManager
					.getListCacheOrLoadSeriaByKey(Constants.FSKEY_NEWlISTS);
			if (screenNews != null && screenNews.getNewsCount() > 0) {
				LoadScreenImage(screenNews, false);
			} else {
				CacheDataManager
						.deleteSeriaFile(Constants.FSKEY_NEWlISTS);
			}
		} else {
			MyLog.i("ydy",
					"isDataValidate"
							+ CacheDataManager
									.isDataValidate(Constants.FSKEY_NEWlISTS));
			if (NetHeadUtils.isNetWorking(mContext)) {
				MyLog.e("ydy", "setTodayDeskPictureNum*************11111");
				Calendar now = Calendar.getInstance();
				int hour = now.get(Calendar.HOUR_OF_DAY);
				if (hour < 6 && mRq_time == RQ_TIME) {// 将请求服务器压力从２４点后五分钟内扩散到５个小时内，５点之后频率不变（这一块注意测试）
					Random r = new Random();
					int val = RANDOMTIME - hour * 60 * 60 * 1000;
					if (val > 0) {
						int random = r.nextInt(val);
						if (random <= 0 || random > RANDOMTIME) {
							random = 30 * 60 * 1000;
						}
						mRq_time = random;
						MyLog.i("wmm", "random  :  " + mRq_time);
					}
					timerHandler.removeCallbacks(timeRunnable);
					timerHandler.postDelayed(timeRunnable, mRq_time);
					MyLog.e("ydy", "hourtime===" + hour + "mRq_time=="
							+ mRq_time);
				} else {
					mRq_time = RQ_TIME;
					// 避免nullpointer
					RequestLockscreenAd(REQUEST_NUM, screenNews == null ? 0
							: screenNews.getMaxID());// 请求20个广告
				}
			}
		}
	}

	private synchronized void RequestLockscreenAd(int adNums, int maxId) {
		MyLog.i("wmm", "RequestLockscreenAd");
		JSONObject request = new JSONObject();
		try {
			request.put("app_key", "391ef58892588b6c");
			request.put("small_img", "208x128");
			request.put("large_img", ProductInfoUtils
					.getScreenWithOrHeight(mContext));

			request.put("number", adNums);
			if (maxId > 0) {
				request.put("max_id", maxId);
			}
			// request.put("lockscreen_show", 1);
			request.put("time", System.currentTimeMillis());
			// request.put("sign ", KingsSystemUtils.getSignature());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		NetConnectTask netTask = NetworkTask.requestMainPageList(this,
				request.toString());

		netTask.setListener(new TaskListener() {

			@Override
			public void onNoNetworking() {

			}

			@Override
			public void onNetworkingError() {

			}

			@Override
			public void onPostExecute(byte[] bytes) {
				MyLog.d("jyh", "requestScreenAd-----------onPostExecute: "
						+ new String(bytes));
				MainList newslist = null;
				try {
					JSONObject result = new JSONObject(new String(bytes));
					if (200 == result.getInt("errno")) {
						SharePreferenceSdkData.setLastRequestTime(
								mContext,
								System.currentTimeMillis());
					}
					JSONArray dataList = result.optJSONArray("data");
					newslist = MainList.parse(dataList);
					// 服务器没有返回数据，不进行任何处理
					if (newslist.getNewsCount() == 0) {
						return;
					}

				} catch (IOException e) {
					e.printStackTrace();
					return;
				} catch (JSONException e) {
					e.printStackTrace();
					return;
				}

				// 如果服务器返回的有效数据小于20，则将本地的数据与新数据进行合并
				if (newslist.getNewsCount() < 20 && screenNews != null
						&& screenNews.getNewsCount() > 0) {
					List<MainNews> newNews = newslist.getNewslist();
					List<MainNews> oldNews = screenNews.getNewslist();
					for (MainNews news : oldNews) {
						boolean isContain = false;
						for (MainNews n : newNews) {
							if (news.getId() == n.getId()) {
								isContain = true;
								break;
							}
						}
						if (!isContain) {
							newNews.add(news);
						}
						if (newNews.size() >= 20) {
							break;
						}
					}
					newslist.setNewsCount(newNews.size());
				}
				if (newslist != null && newslist.getNewsCount() > 0)
					screenNews = newslist;
				if (screenNews != null && screenNews.getNewsCount() > 0) {
					LoadScreenImage(screenNews, true);
					newsIndex = 0;
				}
			}
		});
	}

	
	//此方法已迁移至TimeRunnableService
	private synchronized void LoadScreenImage(MainList mNews, boolean isUpdate) {
		int loadNum = mNews.getNewsCount();
		// 所用网络环境加载一样数目的图片
		if (!NetHeadUtils.getNetworkType(mContext).equals("wifi")) {
			loadNum = 3;// 3g 2G及４G网络情况 //todo ydy
		}
		if (isLoadChecked
				&& !isUpdate
				&& SharePreferenceSdkData
						.getTodayDeskPictureNum(mContext) == loadNum) {// 在同等待网络
			return;
		}
		MyLog.e("ydy", "ScreenLockService *****LoadScreenImage loadNum=="
				+ loadNum);
		if (isUpdate) {
//			mDowloadPicIndex = SharePreferenceSdkData
//					.getTodayDeskPictureIndex(mContext);
			SharePreferenceSdkData.setTodayDeskPictureNum(
					mContext, -1);
			SharePreferenceSdkData.setTodayDeskPictureIndex(
					mContext, -1);
			isLoadChecked = false;
		}
		mDowloadingList = mNews.getNewslist();
		int size = loadNum;

		ImageLoader imageLoader = ImageLoader
				.getInstance(mContext);
		imageLoader.setmILoadedFinishLister(new ILoadedFinishLister() {

			@Override
			public void dowloadOk(String url) {
				if (mDowloadingList != null) {
					for (int i = 0; i < mDowloadingList.size(); i++) {
						if (i >= mDowloadingList.size())
							break;
						String imageUrl = mDowloadingList.get(i)
								.getLargeImageUrl();
						if (null == imageUrl || imageUrl.equals("null")) {
							continue;
						} else {
							if (url.equalsIgnoreCase(imageUrl)) {
								
								int curIndex = SharePreferenceSdkData
										.getTodayDeskPictureIndex(mContext);
								if (i >= curIndex) {
									SharePreferenceSdkData
											.setTodayDeskPictureIndex(
													mContext, i);// 记录脚标
									isLoadedAll = false;
									SharePreferenceSdkData.setIsLoaded(mContext, false);
								}
								if (i == mDowloadingList.size() - 1) {
//									mDowloadPicIndex = -1;
								}
							}
						}
					}
				}
			}
		});

		int loadIndex = -1;
		int totalLoad = 0;
		for (int i = 0; i < mDowloadingList.size(); i++) {
			if (i >= mDowloadingList.size())
				break;
			String imageUrl = mDowloadingList.get(i).getLargeImageUrl();
			if (null == imageUrl || imageUrl.equals("null")) {
				if (size >= 3 && size < mDowloadingList.size()) {
					size++;
				}
				continue;
			}

			// String imageName = FileUtils.getFileName(imageUrl);
			// String filePath = Constants.FOLDER_PICTURE + File.separator
			// + imageName;
			// File file = new File(filePath);
			File file = null;
			try {
				file = SdcardFileUtil.getFile(
						ImageLoader.LOCK_SCREEN_PICTURE, imageUrl);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			MyLog.i("wmm", "file is exists " + file.exists());
			if (file.exists()) {
				loadIndex = i;
				totalLoad++;
				File blurfile = null;
				try {
					blurfile = SdcardFileUtil.getFile(
							ImageLoader.LOCK_BLUR_PICTURE, imageUrl);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (!blurfile.exists()) {
					ImageUtils.makeBlurAndSaveFile(file,
							mContext);
				}

			} else {
				if (i < size) {// size主要控制wifi的下载
					MyLog.i("ydy",
							"ScreenLockService *****LoadScreenImage ******"
									+ imageUrl);
					imageLoader.queuePhoto(imageUrl, null,
							ImageLoader.LOCK_SCREEN_PICTURE);
				}
			}

			File smallImageFile = null;
			try {
				smallImageFile = SdcardFileUtil.getFile(
						ImageLoader.LOCK_DESK_ICON,
						mDowloadingList.get(i).getSmallImageUrl());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (!smallImageFile.exists()) {
				if (i < size) {
					// 判断news类型，是否下载
					if (SHOW_SMALL_IMAGE.equals(mDowloadingList.get(i)
							.getShowSmallImage())) {
						imageLoader.queuePhoto(mDowloadingList.get(i)
								.getSmallImageUrl(), null,
								ImageLoader.LOCK_DESK_ICON);
					}
				}
			}
		}

		if (loadIndex != -1 && !isUpdate) {
			isLoadChecked = true;
			SharePreferenceSdkData.setTodayDeskPictureIndex(
					mContext, loadIndex);// 记录脚标
			SharePreferenceSdkData.setTodayDeskPictureNum(
					mContext, totalLoad);// 记录已经加载过数据量
		}

		if (isUpdate) {
			MyLog.e("ydy", "ScreenLockService *****loadOK save seria file");
			CacheDataManager.setListCacheAndWriteByKey(
					Constants.FSKEY_NEWlISTS, mNews);
		}

	}

	private void DisableKeyGruadPro() {

		try {
			if (mKeyguardLock != null) {
				mKeyguardLock.disableKeyguard();
				MyLog.i("ydy",
						" ScreenLockService initKeyGruadPro disableKeyguard");
			}
		} catch (Exception e) {
			mKeyguardLock = mKeyguardManager.newKeyguardLock(this.getClass()
					.getName());
			mKeyguardLock.disableKeyguard();
			e.printStackTrace();
		}

	}

	private void EnableKeyGruadPro() {
		try {
			if (mKeyguardLock != null) {
				mKeyguardLock.reenableKeyguard();
				MyLog.i("ydy", " ScreenLockService reenableKeyguard");
			}
		} catch (Exception e) {
			mKeyguardLock = mKeyguardManager.newKeyguardLock(this.getClass()
					.getName());
			mKeyguardLock.reenableKeyguard();
			e.printStackTrace();
		}
	}

	private void inittLayoutParam() {

		mLp.width = LayoutParams.MATCH_PARENT;
		mLp.height = LayoutParams.MATCH_PARENT;
		mLp.type = LayoutParams.TYPE_SYSTEM_ERROR;
		mLp.format = PixelFormat.RGBA_8888;
		mLp.flags = LayoutParams.FLAG_FULLSCREEN|LayoutParams.FLAG_LAYOUT_IN_SCREEN;
		mLp.gravity = Gravity.LEFT | Gravity.TOP;
		mLp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;

	}

	public void initViews() {
		LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mMask = inflate.inflate(R.layout.lock_mask, null);
		initLockView();
		mLockView.setFocusable(true);// deal with power key
		mLockView.setFocusableInTouchMode(true);
		mLockView.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
				MyLog.i("ydy4", "******arg1==" + arg1);
				if (arg1 == KeyEvent.KEYCODE_POWER) {
					try {
						hideKeyguardView();// repeat remove may has exception
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				return false;
			}
		});
		mStatusViewManager = new StatusViewManager(mLockView,
				this.mContext);
		// setKeyguradView();

	}

	private boolean isPictureReadyed() {
		if (!hasAdPicture()) {
			return false;
		}
		return true;

	}

	private Runnable mPowerOffRunnable = new Runnable() {
		public void run() {
			try {
				setKeyguradView();
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}
	};

	private Runnable mRefreshRunnable = new Runnable() {

		@Override
		public void run() {
			try {
				if (isShowKeyGuard)
					return;
				isShowKeyGuard = true;
				mWinManager.addView(mLockView, mLp);
				setKeyguradView();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	};

	private void setKeyguradView() {
		lastShowTime = System.currentTimeMillis();
		if ((SharePreferenceSdkData
				.getTodayDeskPictureIndex(mContext) == -1)) {
			MyLog.i("setImage", "time : "+System.currentTimeMillis() + "setDefaultScreen" );
//			MyLog.i("ydy4", "setDefault screen " + mDowloadPicIndex);
			boolean rtn = setDefaultScreen();
			MyLog.e("wmm", "first  setDefaultScreen  : "+rtn);
			if (!rtn) {
				hideKeyguardView();
			}
			mLockView.setNewsItemVisibility(View.GONE);
		} else {
			MyLog.i("ydy4", "ScreenLockService setKeyguradView loaddata");
			long startTime = System.currentTimeMillis();
			if (SetScreenImage()) {
				MyLog.i("jyh", "~~~~~~~SetScreenImage() time range is : "
						+ (System.currentTimeMillis() - startTime)
						+ "  ~~~~~~~");

				mLockView.setNewsItemVisibility(View.VISIBLE);
			} else {
				MyLog.e("ydy", "setTodayDeskPictureNum*************333333");
				MyLog.i("setImage", "time : "+System.currentTimeMillis() + "SetScreenImage is failed");
				SharePreferenceSdkData.setTodayDeskPictureIndex(
						mContext, -1);

				if (!setDefaultScreen()) {
					hideKeyguardView();
				}
				mLockView.setNewsItemVisibility(View.GONE);
			}
		}

	}
	
	private String getTime(){
		return DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME);
	}

	private void preMakeWallPaper() {
		File file = new File(Constants.FOLDER_PICTURE + DEFAULT_WALLPAER_BLUR);

		if (!file.exists()) {
			Drawable wallDraw = WallpaperManager.getInstance(
					mContext).getDrawable();

			if (wallDraw != null) {
				MyLog.i("ydy4",
						"ScreenLockService preMakeWallPaper make wallpaper!!!!");
				BitmapDrawable bd = (BitmapDrawable) wallDraw;
				Bitmap newBmp = ImageUtils.generateBitmap(bd.getBitmap(),
						screenWidth, screenHeight);
				ImageUtils.saveBlurBitmap(newBmp, DEFAULT_WALLPAER,
						mContext);
			}
		}

	}

	private boolean setDefaultScreen() {
		File file = new File(Constants.FOLDER_PICTURE + DEFAULT_WALLPAER);
		if (file.exists()) {
			return mLockView.setDefaultWallpager();
		} else {
			return false;
		}
	}

	private boolean hasAdPicture() {
		File file = new File(Constants.FOLDER_PICTURE);
		if (file.exists()) {
			File[] list = file.listFiles();
			if (list != null && list.length > 0)
				return true;
		}
		return false;
	}

	public synchronized void initLockView() {
		mLockView = null;
		mLockView = new ScreenLockView(ScreenLockService.this);
		mLockView.setLockListener(new LockListener() {

			@Override
			public void itemClick() {
				UserCountHabit.setUserCount(ScreenLockService.this,
						UserCountHabit.DESK_LEFT);
				onNewsClick();
				hideKeyguardView();
			}

			@Override
			public void compute(float tx, boolean isFling) {
				if (tx > screenWidth >> 1 || isFling) {
					mLockView.unLock();
				} else {
					mLockView.resetView();
				}
			}

			@Override
			public void unlock() {
				hideKeyguardView();
			}
		});
	}
	
	
	private void onNewsClick(){
		if(curNews == null){
			return;
		}
		switch (curNews.getSlide2browser()) {
		case MainList.TYPE_OPEN_APP:
			Intent app = getPackageManager().getLaunchIntentForPackage(curNews.getPname()); 
			try {
				if(app != null){
					app.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(app);
				}else{
					Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(curNews.getAppUrl()));
					urlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(urlIntent);
				}
			} catch (ActivityNotFoundException e) {
				e.printStackTrace();
				Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(curNews.getAppUrl()));
				urlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(urlIntent);
			}
			break;

		default:
			Intent intent = new Intent();
			if(curNews.getEngineType() == 1){
				intent.setClass(mContext, GamePlayActivity.class);
			}else{
				intent.setClass(mContext, DetailPageActivity.class);
			}
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("curNews", curNews);
			intent.putExtra(Constants.FROM, Constants.FROM_SCREEN);
			if(!TextUtils.isEmpty(curNews.getDownLoadLink())){
				MyDownloadManager.getInstance().download(getApplicationContext(), curNews.getDownLoadLink());
			}
			startActivity(intent);
			break;
		}
	}

	public void startAnim() {
		mLockView.screenOn();
	}

	private boolean isAnimating;


	@Override
	public void onStart(Intent intent, int startId) {
		// 设置超时时间
		setScreenOffTime(30 * 60 * 60 * 1000);
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		MyLog.d(TAG, "onDestroy()");
		unregisterComponent();
		hideKeyguardView();
		mHandler.removeCallbacks(timeRunnable);
		mHandler.removeCallbacks(mRefreshRunnable);
		if (FLAG_NOTICE)
			stopForegroundCompat();

	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		MyLog.d(TAG, "onStartCommand()");
		return Service.START_STICKY;
	}

	private synchronized boolean SetScreenImage() {
		MainList mNews = (MainList) CacheDataManager
				.getListCacheOrLoadSeriaByKey(Constants.FSKEY_NEWlISTS);
		MyLog.i("jyh", "~~~~~NewsList mNews is ~~~~" + mNews);
		boolean result = false;
		if (mNews != null) {
			List<MainNews> mList = mNews.getNewslist();
			int size = mList.size();
			int num = 0;
			int tmpIndex = 0;
			if (size == 0)
				return result;
			int prefeNum = SharePreferenceSdkData
					.getTodayDeskPictureIndex(mContext);

			if (prefeNum == -1) {
				return result;
			}

			int loadPictureIndex = prefeNum;
			int times = 0;
			while (!result) {
				times++;
				if (newsIndex == 0) {
					newsIndex = SharePreferenceSdkData
							.getLastNewsIndex(mContext);
				}
				MyLog.i("wmm", "newsIndex : " + newsIndex
						+ "    loadPictureIndex : " + loadPictureIndex);
				if (newsIndex > loadPictureIndex) {
					isLoadedAll = true;
					SharePreferenceSdkData.setIsLoaded(mContext, true);
					newsIndex = 0;
				}
				MyLog.i("ydy", "isLoadedAll  " + isLoadedAll);
				tmpIndex = newsIndex;
				newsIndex++;
				SharePreferenceSdkData.setLastNewsIndex(
						mContext, newsIndex);
				if (tmpIndex < 0)
					tmpIndex = 0;
				if (tmpIndex >= size)
					tmpIndex = size - 1;

				MyLog.i("wmm", "tmpIndex :" + tmpIndex);
				MainNews news = mList.get(tmpIndex);
				if (news.getLock_show() == 1 && mLockView.refreshNews(news)) {
					num++;
					curNews = news;
				} else {
					if (times > loadPictureIndex) {// 防止死循环及数据破坏
						SharePreferenceSdkData.setTodayDeskPictureIndex(
								mContext, -1);
						break;

					}
					continue;
				}

				if (num >= 1) {
					result = true;
					break;
				}

				

			}
		}

		if (result && curNews != null) {
			if (isShowKeyGuard) {
				MyLog.e("ydy2",
						"****ScreenLockService ***** write showId start id=="
								+ curNews.getId());
				UserCountHabit.setUserCount(ScreenLockService.this,
						UserCountHabit.ADSHOW_NUM + curNews.getId());
			}
		}
		return result;
	}

	private long lastShowTime;
	private BroadcastReceiver mScreenOnOrOffReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			MyLog.d("ydy", "mScreenOffReceiver()" + intent.getAction());
			if (intent.getAction().equals("android.intent.action.SCREEN_OFF")) {
				UserCountHabit.setUserCount(ScreenLockService.this,UserCountHabit.SCREEN_OFF);//统计灭屏次数
				if (mLockView != null) {
					MyLog.i("wmm:", "isShowKeyGuard : " + isShowKeyGuard
							+ "    isCalling  " + isCalling
							+ "       is idle :" + isIDLE());
					if (isCalling && !isIDLE()) {
						return;
					}

					// 解系统锁
					if (!isShowKeyGuard) {
						mHandler.post(mRefreshRunnable);
						MyLog.i("jyh",
								"~~~~~~~~~~~~~before post   "
										+ System.currentTimeMillis()
										+ "    ~~~~~~~~~~~~~~");
					} else {
						MyLog.i("ydy",
								"ScreenLockService onReceive isShowKeyGuard==trye");
						if (System.currentTimeMillis() - lastShowTime < 5000) {//todo guoguangxiang //出测试版本
							return;
						}
						mHandler.post(mPowerOffRunnable);
					}
				}
			}
			// 采用在onCreate方法中判断当前屏幕状态的方法，添加锁屏
			else if (intent.getAction().equals(
					"android.intent.action.SCREEN_ON")) {
				UserCountHabit.setUserCount(ScreenLockService.this,UserCountHabit.SCREEN_ON);//统计屏幕点亮次数
				EnableKeyGruadPro();
				DisableKeyGruadPro();
				startAnim();
			}
		}
	};

	public void registerComponent() {
		MyLog.d(TAG, "registerComponent()");
		IntentFilter mScreenOnOrOffFilter = new IntentFilter();
		mScreenOnOrOffFilter.addAction("android.intent.action.SCREEN_ON");
		mScreenOnOrOffFilter.addAction("android.intent.action.SCREEN_OFF");
		registerReceiver(mScreenOnOrOffReceiver,mScreenOnOrOffFilter);
		registerOutCallReceiver();
		screenRegisterFlag = true;

		IntentFilter batteryFilter = new IntentFilter();
		batteryFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
		batteryFilter.addAction(Intent.ACTION_BATTERY_LOW);
		batteryFilter.addAction(Intent.ACTION_BATTERY_OKAY);
		registerReceiver(batteryReceiver, batteryFilter);
		batteryRegisterFlag = true;

		IntentFilter wifiFilter = new IntentFilter();
		wifiFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
		wifiFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(wifiReceiver, wifiFilter);
		wifiRegisterFlag = true;
	}

	private boolean isIDLE() {
		long start = System.currentTimeMillis();
		boolean isIDLE = false;
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		switch (tm.getCallState()) {
		case TelephonyManager.CALL_STATE_IDLE:
			isIDLE = true;
			break;
		case TelephonyManager.CALL_STATE_OFFHOOK:
		case TelephonyManager.CALL_STATE_RINGING:
			break;
		default:
			break;
		}
		MyLog.i("wmm", "is idle time is "
				+ (System.currentTimeMillis() - start));
		return isIDLE;
	}

	public void unregisterComponent() {
		MyLog.d(TAG, "unregisterComponent()");
		if (screenRegisterFlag) {
			unregisterReceiver(mScreenOnOrOffReceiver);
			screenRegisterFlag = false;
		}
		if (batteryRegisterFlag) {
			unregisterReceiver(batteryReceiver);
			batteryRegisterFlag = false;
		}
		if (wifiRegisterFlag) {
			unregisterReceiver(wifiReceiver);
			wifiRegisterFlag = false;
		}
		if (tpm != null) {
			tpm.listen(mInCallReceiver, PhoneStateListener.LISTEN_NONE);
		}
	}

	class InCallReceiver extends PhoneStateListener {

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE: // 空闲
				isCalling = false;
				break;
			case TelephonyManager.CALL_STATE_RINGING: // 来电
				try {
					isCalling = true;
					hideKeyguardView();
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK: // 摘机（正在通话中）
				isCalling = true;
				break;
			}
		}

	}

	private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			int status = intent.getIntExtra("status", 0);
			int level = intent.getIntExtra("level", 0);
			mLockView.refreshBatteryLevel(status, level);
		}
	};

	private BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// wifi信号强度发生变化
			if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)
					|| WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
				WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
				int status = wm.getWifiState();
				mLockView.refreshWifiLevel(status, WifiManager.calculateSignalLevel(
						wm.getConnectionInfo().getRssi(), 3));
			} else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
				ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo info = cm.getActiveNetworkInfo();
				if (info != null && info.isAvailable()) {
					mLockView.refreshNetType(NetUtil.getNetType(context));
				} else {
					mLockView.refreshNetType(NetUtil.NETWORK_UNKOWN);
				}
			}
		};
	};

	private void registerOutCallReceiver() {
		// 获取电话通讯服务
		tpm = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);
		// 创建一个监听对象，监听电话状态改变事件
		tpm.listen(mInCallReceiver, PhoneStateListener.LISTEN_CALL_STATE);
	}

	// 设置前台服务
	private Object[] mStartForegroundArgs = new Object[2];
	private Object[] mStopForegroundArgs = new Object[1];
	// 声明跟前台服务相关的几个变量
	private static final Class<?>[] mStartForegroundSignature = new Class[] {
			int.class, Notification.class };
	private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };
	private Method mStartForeground;
	private Method mStopForeground;

	private void initForegroundCompat() {
		try {
			mStartForeground = getClass().getMethod("startForeground",
					mStartForegroundSignature);
			mStopForeground = getClass().getMethod("stopForeground",
					mStopForegroundSignature);
		} catch (NoSuchMethodException e) {
			mStartForeground = null;
		}

	}

	private NotificationManager getNotificationManager(Context context) {
		return (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
	}

	private Notification getNotification(String content) {
		Notification no = new Notification();
		no.icon = R.drawable.ic_launcher;
		no.flags = Notification.FLAG_NO_CLEAR;
		no.contentView = new RemoteViews(this.getPackageName(),
				R.layout.notification_item);
		no.contentView.setTextViewText(R.id.tv_noti_content, content);
		Intent i = new Intent(mContext, LockMainActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent contentIntent = PendingIntent.getActivity(
				mContext, 0, i, 0);

		// Set the info for the views that show in the notification panel.
		no.setLatestEventInfo(mContext, getResources()
				.getString(R.string.lock_app_name), content, contentIntent);

		return no;
	}

	// 设置为前台服务
	private void startForegroundCompat(int id, Notification notification) {
		// If we have the new startForeground API, then use it.
		initForegroundCompat();

		if (mStartForeground != null) {
			mStartForegroundArgs[0] = Integer.valueOf(id);
			mStartForegroundArgs[1] = notification;
			try {
				mStartForeground.invoke(ScreenLockService.this,
						mStartForegroundArgs);
			} catch (Exception e) {
			}
			return;
		}
		getNotificationManager(ScreenLockService.this).notify(
				NOTIFY_NETCOUNTER_ID, notification);
		startForeground(id, notification);
	}

	// 停止前台服务
	private void stopForegroundCompat() {

		// If we have the new stopForeground API, then use it.
		if (mStopForeground != null) {
			mStopForegroundArgs[0] = Boolean.TRUE;
			try {
				mStopForeground.invoke(ScreenLockService.this,
						mStopForegroundArgs);
			} catch (InvocationTargetException e) {
			} catch (IllegalAccessException e) {
			}
			return;
		}

		stopForeground(true);
	}

}
